<template>
  <div class="activity-list-container">
    <el-card>
      <!-- 页面标题 -->
      <template #header>
        <div class="card-header">
          <h2 class="page-title">活动管理</h2>
          <el-button 
            type="primary" 
            @click="showCreateDialog = true"
            v-if="userStore.hasPermission(ALL_PERMISSIONS.ACTIVITY_CREATE)"
          >
            <el-icon><Plus /></el-icon>
            创建活动
          </el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="活动名称">
            <el-input 
              v-model="searchForm.search" 
              placeholder="搜索活动名称或描述"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
              <el-option label="进行中" value="ACTIVE" />
              <el-option label="未开始" value="INACTIVE" />
              <el-option label="已完成" value="COMPLETED" />
              <el-option label="已取消" value="CANCELLED" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 活动列表 -->
      <el-table 
        :data="activityList" 
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="活动信息" min-width="300">
          <template #default="{ row }">
            <div class="activity-info">
              <div class="activity-name">{{ row.name }}</div>
              <div class="activity-description" v-if="row.description">
                {{ row.description }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="时间" width="200">
          <template #default="{ row }">
            <div class="activity-time">
              <div>开始: {{ formatDateTime(row.startTime) }}</div>
              <div>结束: {{ formatDateTime(row.endTime) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status) as any">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="参与艺人" width="120">
          <template #default="{ row }">
            <el-tag type="info">{{ row._count?.activityArtists || 0 }} 人</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="总投票" width="120">
          <template #default="{ row }">
            <el-tag type="success">{{ row._count?.votes || 0 }} 票</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="viewActivity(row)"
              v-if="userStore.hasPermission(ALL_PERMISSIONS.ACTIVITY_READ)"
            >
              查看
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="editActivity(row)"
              v-if="userStore.hasPermission(ALL_PERMISSIONS.ACTIVITY_UPDATE)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteActivity(row)"
              v-if="userStore.hasPermission(ALL_PERMISSIONS.ACTIVITY_DELETE)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑活动对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      :title="isEdit ? '编辑活动' : '创建活动'"
      width="600px"
    >
      <el-form 
        ref="formRef"
        :model="activityForm" 
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="activityForm.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input 
            v-model="activityForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入活动描述"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="activityForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="activityForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="isEdit">
          <el-select v-model="activityForm.status" placeholder="选择状态">
            <el-option label="进行中" value="ACTIVE" />
            <el-option label="未开始" value="INACTIVE" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="横幅图片" prop="bannerImage">
          <el-input v-model="activityForm.bannerImage" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="活动规则" prop="rules">
          <el-input 
            v-model="activityForm.rules" 
            type="textarea" 
            :rows="4"
            placeholder="请输入活动规则"
          />
        </el-form-item>
        <el-form-item label="最大投票数" prop="maxVotesPerUser">
          <el-input-number 
            v-model="activityForm.maxVotesPerUser" 
            :min="1" 
            :max="10"
            placeholder="每个用户最大投票数"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { activityApi } from '@/api'
import { ALL_PERMISSIONS } from '@/constants/permissions'
import type { Activity } from '@/types'
import { formatDateTime } from '@/utils/format'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const showCreateDialog = ref(false)
const isEdit = ref(false)
const activityList = ref<Activity[]>([])
const formRef = ref()

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

const searchForm = reactive({
  search: '',
  status: ''
})

const activityForm = reactive({
  id: 0,
  name: '',
  description: '',
  startTime: '',
  endTime: '',
  status: 'ACTIVE' as const,
  bannerImage: '',
  rules: '',
  maxVotesPerUser: 1
})

const formRules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  maxVotesPerUser: [
    { required: true, message: '请设置最大投票数', trigger: 'blur' }
  ]
}

// 获取活动列表
const fetchActivities = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      search: searchForm.search || undefined,
      status: searchForm.status || undefined
    }
    const response = await activityApi.getList(params)
    activityList.value = response.data.data
    pagination.total = response.data.pagination.total
    pagination.page = response.data.pagination.page
    pagination.limit = response.data.pagination.limit
  } catch (error) {
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchActivities()
}

// 重置搜索
const handleReset = () => {
  searchForm.search = ''
  searchForm.status = ''
  pagination.page = 1
  fetchActivities()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchActivities()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchActivities()
}

// 查看活动
const viewActivity = (activity: Activity) => {
  // 跳转到活动详情页面
  router.push(`/activities/${activity.id}`)
}

// 编辑活动
const editActivity = (activity: Activity) => {
  isEdit.value = true
  Object.assign(activityForm, activity)
  showCreateDialog.value = true
}

// 删除活动
const deleteActivity = async (activity: Activity) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除活动"${activity.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await activityApi.delete(activity.id)
    ElMessage.success('删除成功')
    fetchActivities()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await activityApi.update(activityForm.id, activityForm)
      ElMessage.success('更新成功')
    } else {
      await activityApi.create(activityForm)
      ElMessage.success('创建成功')
    }
    
    showCreateDialog.value = false
    fetchActivities()
    resetForm()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(activityForm, {
    id: 0,
    name: '',
    description: '',
    startTime: '',
    endTime: '',
    status: 'ACTIVE' as const,
    bannerImage: '',
    rules: '',
    maxVotesPerUser: 1
  })
  isEdit.value = false
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: 'success',
    INACTIVE: 'info',
    COMPLETED: 'warning',
    CANCELLED: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: '进行中',
    INACTIVE: '未开始',
    COMPLETED: '已完成',
    CANCELLED: '已取消'
  }
  return statusMap[status] || status
}

// 初始化
onMounted(() => {
  fetchActivities()
})
</script>

<style scoped>
.activity-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.activity-info {
  .activity-name {
    font-weight: bold;
    color: #333;
    margin-bottom: 5px;
  }
  
  .activity-description {
    color: #666;
    font-size: 14px;
    line-height: 1.4;
  }
}

.activity-time {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>
